use eframe::egui;
use crate::app::App;
use crate::ui::{dashboard, servers, settings, speed_test};
use crate::models::View;

// 用于UI组件回传的事件
pub enum AppEvent {
    None,
    ToggleConnection,
    SelectServer(usize),
    AddServer,
    EditServer(usize),
    SaveServer(crate::models::ServerConfig, Option<usize>),
    DeleteServer(usize),
    SetDarkMode(bool),
    SetPrimaryColor((u8, u8, u8)),
    SetAutoStart(bool),
    SetAutoConnect(bool),
    EditSocks5Port,
    EditHttpPort,
    SpeedTest,
    ClearSpeedTest,
    SaveConfig,
    ResetConfig,
}

impl eframe::App for App {
    fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
        // 应用主题
        self.theme.apply_to_ctx(ctx);
        
        // 如果连接中，更新连接时间
        if self.connected {
            let now = std::time::Instant::now();
            let elapsed = now.duration_since(self.last_update).as_secs();
            self.connection_time += elapsed;
            self.last_update = now;
            
            // 定期重绘界面以更新时间显示
            ctx.request_repaint_after(std::time::Duration::from_secs(1));
        }
        
        let mut event = AppEvent::None;
        
        // 显示服务器对话框（如果打开）
        if let Some((server, index)) = self.server_dialog.show(ctx) {
            event = AppEvent::SaveServer(server, index);
        }
        
        // 全局布局
        egui::SidePanel::left("nav_panel")
            .exact_width(self.sizes.nav_bar_width)
            .resizable(false)
            .show(ctx, |ui| {
                ui.vertical_centered(|ui| {
                    ui.add_space(16.0);
                    // 应用标题
                    ui.heading(
                        egui::RichText::new("BanLSProxy")
                            .size(22.0)
                            .color(self.theme.primary)
                            .strong()
                    );
                    ui.add_space(8.0);
                    
                    // 连接状态指示器
                    let status_text = if self.connected { "已连接" } else { "未连接" };
                    let status_color = if self.connected { self.theme.success } else { self.theme.error };
                    ui.label(
                        egui::RichText::new(status_text)
                            .color(status_color)
                            .size(14.0)
                    );
                    
                    ui.add_space(32.0);
                });
                
                ui.separator();
                ui.add_space(16.0);
                
                // 导航菜单
                self.render_nav_menu(ui);
                
                ui.with_layout(egui::Layout::bottom_up(egui::Align::Center), |ui| {
                    ui.add_space(8.0);
                    
                    // 保存配置按钮
                    if ui.button("保存配置").clicked() {
                        event = AppEvent::SaveConfig;
                    }
                    
                    ui.add_space(8.0);
                });
            });
        
        // 主内容区域
        egui::CentralPanel::default().show(ctx, |ui| {
            // 渲染视图组件，收集事件
            match self.current_view {
                View::Dashboard => if let Some(evt) = self.render_dashboard(ui) {
                    event = evt;
                },
                View::Servers => if let Some(evt) = self.render_servers(ui) {
                    event = evt;
                },
                View::Settings => if let Some(evt) = self.render_settings(ui) {
                    event = evt;
                },
                View::SpeedTest => if let Some(evt) = self.render_speed_test(ui) {
                    event = evt;
                },
            }
        });
        
        // 处理事件
        self.handle_event(event);
    }
}

impl App {
    // 获取主题的只读引用，避免重复借用self
    pub fn get_theme(&self) -> &crate::ui::theme::AppTheme {
        &self.theme
    }
    
    // 处理UI事件
    fn handle_event(&mut self, event: AppEvent) {
        match event {
            AppEvent::None => {},
            AppEvent::ToggleConnection => self.toggle_connection(),
            AppEvent::SelectServer(idx) => {
                if idx < self.servers.len() {
                    self.current_server_idx = Some(idx);
                }
            },
            AppEvent::AddServer => {
                self.server_dialog.open_add();
            },
            AppEvent::EditServer(idx) => {
                if idx < self.servers.len() {
                    let server = self.servers[idx].clone();
                    self.server_dialog.open_edit(server, idx);
                }
            },
            AppEvent::SaveServer(server, idx) => {
                if let Some(index) = idx {
                    // 编辑现有服务器
                    if index < self.servers.len() {
                        self.servers[index] = server;
                    }
                } else {
                    // 添加新服务器
                    self.servers.push(server);
                    self.current_server_idx = Some(self.servers.len() - 1);
                }
            },
            AppEvent::DeleteServer(idx) => {
                if self.servers.len() > 1 && idx < self.servers.len() {
                    self.servers.remove(idx);
                    if self.current_server_idx == Some(idx) {
                        self.current_server_idx = Some(0);
                    } else if let Some(current_idx) = self.current_server_idx {
                        if current_idx > idx {
                            self.current_server_idx = Some(current_idx - 1);
                        }
                    }
                }
            },
            AppEvent::SetDarkMode(dark_mode) => {
                self.app_config.dark_mode = dark_mode;
                let primary = self.app_config.primary_color;
                let secondary = self.app_config.secondary_color;
                self.theme = crate::ui::theme::AppTheme::custom_theme(primary, secondary, dark_mode);
            },
            AppEvent::SetPrimaryColor(color) => {
                self.app_config.primary_color = color;
                let is_dark = self.app_config.dark_mode;
                let secondary = self.app_config.secondary_color;
                self.theme = crate::ui::theme::AppTheme::custom_theme(color, secondary, is_dark);
            },
            AppEvent::SetAutoStart(auto_start) => {
                self.app_config.auto_start = auto_start;
            },
            AppEvent::SetAutoConnect(auto_connect) => {
                self.app_config.auto_connect = auto_connect;
            },
            AppEvent::EditSocks5Port => {
                // 这里应该打开端口编辑对话框，简化实现
                // self.app_config.socks5_port = 新端口值;
            },
            AppEvent::EditHttpPort => {
                // 这里应该打开端口编辑对话框，简化实现
                // self.app_config.http_port = 新端口值;
            },
            AppEvent::SpeedTest => {
                // 收集服务器名称并进行测速
                let server_names: Vec<String> = self.servers.iter()
                    .map(|server| server.name.clone())
                    .collect();
                
                for name in server_names {
                    self.run_speed_test(name);
                }
            },
            AppEvent::ClearSpeedTest => {
                self.speed_test_results.clear();
            },
            AppEvent::SaveConfig => {
                if let Err(err) = self.save_config() {
                    eprintln!("保存配置失败: {}", err);
                }
            },
            AppEvent::ResetConfig => {
                self.app_config = crate::models::config::AppConfig::new();
                let is_dark = self.app_config.dark_mode;
                let primary = self.app_config.primary_color;
                let secondary = self.app_config.secondary_color;
                self.theme = crate::ui::theme::AppTheme::custom_theme(primary, secondary, is_dark);
            },
        }
    }
    
    // 渲染仪表盘
    fn render_dashboard(&self, ui: &mut egui::Ui) -> Option<AppEvent> {
        let mut event = None;
        
        // 仿制Dashboard模块的实现，但捕获点击事件
        dashboard::Dashboard::render(ui, self, self.get_theme());
        
        // 此处简化处理，连接按钮点击事件从响应中获取
        if ui.ctx().input(|i| i.pointer.any_click()) {
            // 检测点击是否在连接按钮区域
            // 这里实际应用中需要从组件中获取实际事件
            let pos = ui.ctx().input(|i| i.pointer.interact_pos());
            if let Some(_pos) = pos {
                if ui.ctx().input(|i| i.pointer.any_released()) {
                    // 这里简化为当有任何点击时触发连接事件
                    // 实际应用中应从组件中获取实际事件
                    event = Some(AppEvent::ToggleConnection);
                }
            }
        }
        
        event
    }
    
    // 渲染服务器管理
    fn render_servers(&self, ui: &mut egui::Ui) -> Option<AppEvent> {
        let mut event = None;
        
        // 仿制ServerPanel模块的实现
        servers::ServersPanel::render(ui, self, self.get_theme());
        
        // 简化处理，仅举例如何返回事件
        event
    }
    
    // 渲染设置
    fn render_settings(&self, ui: &mut egui::Ui) -> Option<AppEvent> {
        let mut event = None;
        
        // 仿制SettingsPanel模块的实现
        settings::SettingsPanel::render(ui, self, self.get_theme());
        
        // 简化处理，仅举例如何返回事件
        event
    }
    
    // 渲染速度测试
    fn render_speed_test(&self, ui: &mut egui::Ui) -> Option<AppEvent> {
        let mut event = None;
        
        // 仿制SpeedTestPanel模块的实现
        speed_test::SpeedTestPanel::render(ui, self, self.get_theme());
        
        // 简化处理，仅举例如何返回事件
        event
    }
    
    // 渲染导航菜单
    fn render_nav_menu(&mut self, ui: &mut egui::Ui) {
        // 只复制当前值，避免可变借用
        let current_view = self.current_view.clone();
        
        // 分隔符和间距
        let spacing = 12.0;
        
        // 导航按钮 - 仪表盘
        if self.nav_button(ui, "仪表盘", current_view == View::Dashboard) {
            self.current_view = View::Dashboard;
        }
        
        ui.add_space(spacing);
        
        // 导航按钮 - 服务器
        if self.nav_button(ui, "服务器", current_view == View::Servers) {
            self.current_view = View::Servers;
        }
        
        ui.add_space(spacing);
        
        // 导航按钮 - 测速
        if self.nav_button(ui, "测速", current_view == View::SpeedTest) {
            self.current_view = View::SpeedTest;
        }
        
        ui.add_space(spacing);
        
        // 导航按钮 - 设置
        if self.nav_button(ui, "设置", current_view == View::Settings) {
            self.current_view = View::Settings;
        }
    }
    
    // 自定义导航按钮
    fn nav_button(&mut self, ui: &mut egui::Ui, text: &str, selected: bool) -> bool {
        // 按钮大小和样式
        let height = 36.0;
        let padding = 16.0;
        let rounding = egui::Rounding::same(8.0);
        
        // 按钮颜色
        let (bg_color, text_color) = if selected {
            (self.theme.primary, self.theme.text)
        } else {
            (egui::Color32::TRANSPARENT, self.theme.text_secondary)
        };
        
        // 添加按钮
        let btn = egui::Button::new(
            egui::RichText::new(text)
                .size(16.0)
                .color(text_color)
        )
        .min_size(egui::Vec2::new(ui.available_width() - padding, height))
        .rounding(rounding)
        .fill(bg_color);
        
        ui.add_space(4.0);
        let response = ui.add(btn);
        ui.add_space(4.0);
        
        response.clicked()
    }
} 